package com.example.service.impl;

import com.example.feignClients.BookClient;
import com.example.feignClients.CategoryClient;
import com.example.feignClients.UserClient;
import com.example.mapper.BorrowMapper;
import com.example.pojo.dto.*;
import com.example.pojo.entity.Borrow;
import com.example.pojo.entity.Category;
import com.example.pojo.entity.Employee;
import com.example.pojo.entity.result.PageResult;
import com.example.pojo.entity.result.Result;
import com.example.pojo.vo.*;
import com.example.service.BorrowService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class BorrowServiceImpl implements BorrowService {
    private final BorrowMapper borrowMapper;
    private final CategoryClient categoryClient;
    private final BookClient bookClient;
    private final UserClient userClient;

    /**
     * 登记借书
     *
     * @param borrowDTO
     */
    @Override
    public void borrow(BorrowDTO borrowDTO) {
        //查询用户
        UserPageQueryDTO userPageQueryDTO = UserPageQueryDTO.builder()
                .page(1)
                .pageSize(5)
                .idNumber(borrowDTO.getIdNumber())
                .build();

        PageResult<UserPageVO> userPageVOPageResult = userClient.pageUser(
                userPageQueryDTO.getPage(),
                userPageQueryDTO.getPageSize(),
                userPageQueryDTO.getSurname(),
                userPageQueryDTO.getSex(),
                userPageQueryDTO.getPhone(),
                userPageQueryDTO.getIdNumber()
        ).getData();

        Integer userId = null;
        //不存在则先注册并获取id
        if (userPageVOPageResult.getTotal() == 0) {
            userId = userClient.insertUser(UserInsertDTO.builder()
                    .surname(borrowDTO.getSurname())
                    .sex(borrowDTO.getSex())
                    .phone(borrowDTO.getPhone())
                    .idNumber(borrowDTO.getIdNumber())
                    .build()).getData().getId();
        } else {
            //存在则直接获取id
            userId = userPageVOPageResult.getRecords().get(0).getId();
        }

        borrowDTO.setUserId(Long.valueOf(userId));

        //设置图书状态
        bookClient.updateById(BookUpdateDTO.builder()
                .id(borrowDTO.getBookId())
                .status(2)
                .build());

        //减少库存
        Result<BookVO> bookVOResult = bookClient.getById(borrowDTO.getBookId());
        Long categoryId = bookVOResult.getData().getCategoryId();
        categoryClient.decrease(categoryId);

        //添加借阅记录
        LocalDateTime now = LocalDateTime.now();
        borrowDTO.setBorrowTime(now);
        borrowDTO.setReturnDeadline(now.plusDays(15));//最迟归还时间为15天
        borrowDTO.setStatus(2);
        borrowMapper.addBorrow(borrowDTO);
    }

    /**
     * 登记还书
     *
     * @param id
     */
    @Override
    public void returnBook(Long id) {
        Borrow borrow = borrowMapper.getById(id);
        if (borrow != null) {
            //修改借阅记录状态
            borrow.setStatus(1);
            borrow.setReturnTime(LocalDateTime.now());
            borrowMapper.updateStatusAndReturnTime(borrow);

            //修改图书状态
            bookClient.updateById(BookUpdateDTO.builder()
                    .id(borrow.getBookId())
                    .status(1)
                    .build());

            //增加库存
            Result<BookVO> bookVOResult = bookClient.getById(borrow.getBookId());
            Long categoryId = bookVOResult.getData().getCategoryId();
            categoryClient.plus(categoryId);
        }
    }

    /**
     * 分页查询借书记录
     *
     * @param borrowPageDTO
     * @return
     */
    @Override
    public PageResult<BorrowPageVO> borrowPageList(BorrowPageDTO borrowPageDTO) {
        //设置分页条件
        PageHelper.startPage(borrowPageDTO.getPage(), borrowPageDTO.getPageSize());

        //执行查询
        List<Borrow> borrowList = borrowMapper.listByQuery(borrowPageDTO);

        List<BorrowPageVO> borrowPageVOList = new ArrayList<>();
        for (Borrow borrow : borrowList) {
            //获取书名
            String bookName = bookClient.getById(borrow.getBookId()).getData().getName();
            //获取用户
            UserVO userVO = userClient.getUserById(borrow.getUserId()).getData();
            String surname = userVO.getSurname();
            String sex = userVO.getSex();
            String phone = userVO.getPhone();
            String appellation = surname + (sex.equals("男") ? "先生" : "女士");

            BorrowPageVO borrowPageVO = new BorrowPageVO();
            BeanUtils.copyProperties(borrow, borrowPageVO);
            //设置书名
            borrowPageVO.setBookName(bookName);
            //设置用户信息
            borrowPageVO.setUser(appellation);
            borrowPageVO.setUserPhone(phone);

            //添加进集合
            borrowPageVOList.add(borrowPageVO);
        }

        Page<Borrow> page = (Page<Borrow>) borrowList;

        //返回分页结果
        return new PageResult<>(page.getTotal(), borrowPageVOList);
    }
}
